package server.demo.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import server.demo.entity.Station;
import server.demo.entity.Ticket;
import server.demo.entity.Train;
import server.demo.repository.StationRepository;
import server.demo.repository.TicketRepository;
import server.demo.repository.TrainRepository;

import java.util.List;
import java.util.Optional;

@Service
@Transactional
public class StationService {
    
    @Autowired
    private StationRepository stationRepository;
    
    @Autowired
    private TicketRepository ticketRepository;
    
    @Autowired
    private TrainRepository trainRepository;
    
    public List<Station> getAllStations() {
        return stationRepository.findAll();
    }
    
    public Optional<Station> getStationById(Long id) {
        return stationRepository.findById(id);
    }
    
    public Optional<Station> getStationByCode(String stationCode) {
        return stationRepository.findByStationCode(stationCode);
    }
    
    public Station createStation(Station station) {
        if (stationRepository.existsByStationCode(station.getStationCode())) {
            throw new RuntimeException("车站代码已存在: " + station.getStationCode());
        }
        return stationRepository.save(station);
    }
    
    public Station updateStation(Long id, Station station) {
        Optional<Station> existingStation = stationRepository.findById(id);
        if (existingStation.isEmpty()) {
            throw new RuntimeException("车站不存在");
        }
        
        Station toUpdate = existingStation.get();
        
        if (!toUpdate.getStationCode().equals(station.getStationCode()) && 
            stationRepository.existsByStationCode(station.getStationCode())) {
            throw new RuntimeException("车站代码已存在: " + station.getStationCode());
        }
        
        toUpdate.setStationCode(station.getStationCode());
        toUpdate.setStationName(station.getStationName());
        toUpdate.setCity(station.getCity());
        
        return stationRepository.save(toUpdate);
    }
    
    public void deleteStation(Long id) {
        if (!stationRepository.existsById(id)) {
            throw new RuntimeException("车站不存在");
        }
        
        // 检查是否有相关的票务记录
        List<Ticket> relatedTickets = ticketRepository.findByStartStationIdOrEndStationId(id, id);
        if (!relatedTickets.isEmpty()) {
            throw new RuntimeException("无法删除车站：该车站存在" + relatedTickets.size() + "张相关票务记录。请先处理相关票务。");
        }
        
        // 检查是否有相关的车次记录
        List<Train> relatedTrains = trainRepository.findByStartStationIdOrEndStationId(id, id);
        if (!relatedTrains.isEmpty()) {
            throw new RuntimeException("无法删除车站：该车站存在" + relatedTrains.size() + "个相关车次。请先删除相关车次。");
        }
        
        stationRepository.deleteById(id);
    }
}